import { ref, computed, resolveDirective } from 'vue'
import { defineStore } from 'pinia'
import axios from '../api/axios'

export const useCalStore = defineStore('cal', () => {
    //要结算的商品列表
    const calGoodsList = ref([])
        //定义计算属性，存放总价
    const total = computed(() => {
        let sum = 0
        calGoodsList.value.forEach((item) => {
            sum += item.num * item.price
        })
        return sum
    })

    //提交订单
    const submitOrder = async() => {
        //构建订单对象
        const order = {
                orderDate: new Date().toLocaleString(),
                goodsList: calGoodsList.value,
                total: total.value
            }
            // 发送请求，将订单信息保存到json文件
        await axios.post('/api/orders/addOrder', order)
    }


    return { calGoodsList, total, submitOrder }
})